package com.feihao.zhou.ThreadSave;

public class Ticket implements Runnable {

    private int ticket = 100;

    @Override
    public void run() {

        while (true) {/*//无锁对象，有线程安全问题，重复票！！！
            if (ticket > 0) { //票还有，则继续卖
                try {
                    Thread.sleep(100);
                    ticket--;
                    System.out.println(Thread.currentThread().getName() + "正在卖票，还有" + ticket + "张票");
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }else {
                break;
            }
        }*/
            synchronized (this) {
                if (ticket > 0) { //票还有，则继续卖
                    try {
                        Thread.sleep(100);
                        ticket--;
                        System.out.println(Thread.currentThread().getName() + "正在卖票，还有" + ticket + "张票");
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                } else {
                    break;
                }
            }
        }

    }
}
